package cn.tedu.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.tedu.entity.User;
import cn.tedu.service.UserService;
import cn.tedu.service.impl.UserServiceImpl;
import cn.tedu.util.CommonValue;

/**
 * Servlet implementation class UserRegisterServlet
 */
public class UserRegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private List<String> contentTypes=new ArrayList<String>();   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserRegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
  //在servlet生命周期开始后,自动调用init方法
  	@Override
  	public void init() throws ServletException {
  		//集合存储允许上传的文件类型
  		contentTypes.add("image/png");
  		contentTypes.add("image/jpg");
  		contentTypes.add("image/bmp");
  		contentTypes.add("image/gif");
  		contentTypes.add("image/jpeg");
  	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			User user=new User();
			// Check that we have a file upload request
			// 检查       我们有一个文件  上传  request
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if(isMultipart) {
				//说明request对象中有附件文件,即有文件上传了
				// Create a factory for disk-based file items
				// 创建   一个 工厂 对于 基于硬盘的 文件  条目/项目
				DiskFileItemFactory factory = new DiskFileItemFactory();

				// Configure a repository (to ensure a secure temp location is used)
				// 配置      一个 仓库     为了确认 一个 安全的 临时  本地  是被使用的
				ServletContext servletContext = this.getServletConfig().getServletContext();
				File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
				factory.setRepository(repository);

				// Create a new file upload handler
				//创建    一个新的文件上传  处理器
				ServletFileUpload upload = new ServletFileUpload(factory);

				// Parse the request
				// 转换  请求对象,即把带有附件的请求对象转换成一个list集合
				List<FileItem> items = upload.parseRequest(request);
				System.out.println(items.size());
				
				// Process the uploaded items
				//处理上传的条目
				Iterator<FileItem> iter = items.iterator();
				while (iter.hasNext()) {
				    FileItem item = iter.next();

				    if (item.isFormField()) {
				        //处理的是非文件域
				    	String name = item.getFieldName();
				        String value = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
				        if ("userName".equals(name)) {
				        	user.setName(value);
						}
				        if ("userPassword".equals(name)) {
				        	user.setPassword(value);
						}
				        if ("userAge".equals(name)) {
				        	user.setAge(Integer.parseInt(value));
						}
				        if ("userAddress".equals(name)) {
				        	user.setAddress(value);
						}
				    } else {
				        //处理的是文件域
				    	String fieldName = item.getFieldName();
				        String fileName = item.getName();
				        String contentType = item.getContentType();
				        boolean isInMemory = item.isInMemory();
				        long sizeInBytes = item.getSize();
				        System.out.println("文件域-->"+fieldName+
				                           "      "+fileName+
				                           "      "+contentType+
				                           "      "+isInMemory+
				                           "      "+sizeInBytes);
				        //解决fileName中带有路径问题
				        if(fileName!=null) {
				        	fileName=FilenameUtils.getName(fileName);
				        }
				        
				        if(contentTypes.contains(contentType)) {
				        	if(sizeInBytes<4194304) {
				        		//上传的文件类型在指定文件类型范围内	
					        	//获取服务器中的存储文件的路径
						        //http://localhost:8080/up_down/upload
						        String realPath=this.getServletContext().getRealPath("/images");
						        System.out.println("realPath-->"+realPath);
						        File file=new File(realPath);
						        if(!file.exists()) {
						        	file.mkdir();//upload文件夹不存在,则创建upload目录
						        }
						        //file是服务器存储文件的路径,fileName是文件名
						        File uploadedFile = new File(file,fileName);
						        item.write(uploadedFile);
						    //能执行到此处,证明文件上传成功了
						        user.setHead(fileName);
				        	}else {
				        		request.setAttribute("msg", "文件太大了");
				        		request.getRequestDispatcher("register.jsp").forward(request, response);
				        		return;
				        	}
				            
				        }else {
				        	request.setAttribute("msg", "文件类型不匹配");
			        		request.getRequestDispatcher("register.jsp").forward(request, response);
				        	return;
				        }	
				        
				        
				    }
				}
				//执行到此处,说明所有的循环结束user对象的数据可以给数据库存储了
				//2.调用注册业务逻辑
				UserService userService=new UserServiceImpl();
				boolean flag=userService.addUser(user);
				
				//3.根据注册业务的返回结果做跳转/响应
				if(flag) {
					//说明注册成功
					//获取session对象
					HttpSession session=request.getSession();
					session.setAttribute("user_name", user.getName());
					session.setAttribute("user_password", user.getPassword());
					response.sendRedirect("login.jsp");
				}else {
					//注册失败
					response.sendRedirect("register.jsp");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
		
		
		
//		//1.获取提交过来的数据
//		String uname=request.getParameter("userName");
//		String upwd=request.getParameter("userPassword");
//		String uage=request.getParameter("userAge");
//		String uaddress=request.getParameter("userAddress");
//		//封装数据给User对象
//		User user=new User();
//		user.setName(uname);
//		user.setPassword(upwd);
//		user.setAge((uage==null || uage=="")? 20 : Integer.parseInt(uage));
//		user.setAddress(uaddress);
//		//其他的表单元素的数据提交给servlet该如何获取
//		//获取性别
//		String sex=request.getParameter("userSex");
//		System.out.println("sex="+sex);
//		//获取爱好
//		String[] hobbys=request.getParameterValues("userHobby");
//		if (hobbys!=null) {
//			for(String hobby:hobbys) {
//				System.out.println(hobby);
//			}
//		}
//		//获取籍贯
//		String jiguan=request.getParameter("userJiGuan");
//		System.out.println(jiguan);
//		//获取备注
//		String comment=request.getParameter("userComment");
//		System.out.println(comment);
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
